<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>活动管理</el-breadcrumb-item>
      <el-breadcrumb-item>活动列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片 -->
    <el-card class="box-card">
      <el-alert :closable="false" title="警告提示的文案" type="warning"></el-alert>
      <el-row class="elrowCate">
        <el-col>
          <span>选择商品</span>
          <el-cascader
            v-model="userCateKeys"
            :options="cateList"
            :props="prop"
            @change="userCateChange"
            clearable
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- tab切换 -->
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            size="mini"
            :disabled="btnDisabled"
            @click="addDialogVisible=true"
          >动态参数</el-button>
          <el-table :data="manyTableDate">
            <el-table-column type="expand" label>
              <template slot-scope="scoped">
                <el-tag v-for="(item, index) in scoped.row.attr_vals" :key="index" closable @close="handleCloseCate(scoped.row,index)">{{item}}</el-tag>
                 <el-input
                  class="input-new-tag"
                  v-if="scoped.row.inputVisible"
                  v-model="scoped.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scoped.row)"
                  @blur="handleInputConfirm(scoped.row)"
                ></el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scoped.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="参数名"></el-table-column>
            <el-table-column width="180px" label="操作">
              <template slot-scope="scoped">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="editAddList(scoped.row)"
                >编辑</el-button>
                <el-button
                  type="danger"
                  icon="el-icon-edit"
                  size="mini"
                  @click="editdelete(scoped.row)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态参数" name="only" :disabled="btnDisabled">
          <el-button
            type="primary"
            size="mini"
            :disabled="btnDisabled"
            @click="addDialogVisible=true"
          >静态参数</el-button>
          <el-table :data="onlyTabData">
            <el-table-column type="expand" label>
              <template slot-scope="scoped">
                <el-tag v-for="(item, index) in scoped.row.attr_vals" :key="index" closable @close="handleCloseCate(scoped.row,index)">{{item}}</el-tag>
                 <el-input
                  class="input-new-tag"
                  v-if="scoped.row.inputVisible"
                  v-model="scoped.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scoped.row)"
                  @blur="handleInputConfirm(scoped.row)"
                ></el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scoped.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column prop="attr_name" label="参数名"></el-table-column>
            <el-table-column width="180px" label="操作">
              <template slot-scope="scoped">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="editAddList(scoped.row)"
                >编辑</el-button>
                <el-button
                  type="danger"
                  icon="el-icon-edit"
                  size="mini"
                  @click="editdelete(scoped.row)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>

      <!-- 权限弹出框 -->
      <el-dialog :title="'提示'+titleText" :visible.sync="addDialogVisible" width="50%">
        <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="120px">
          <el-form-item :label="titleText" prop="attr_name">
            <el-input v-model="addForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addAttr">确 定</el-button>
        </span>
      </el-dialog>

      <!-- 编辑弹出框 -->
      <el-dialog :title="'提示'+titleText" :visible.sync="addEditDialogVisible" width="50%">
        <el-form :model="addEditForm" ref="addEditFormRef" label-width="120px">
          <el-form-item :label="titleText" prop="attr_name">
            <el-input v-model="addEditForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="addEditDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addEditAttr">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>
<script>
export default {
  data () {
    return {
      // 获取参数列表
      cateList: [],
      //  数据双向绑定
      userCateKeys: [],
      prop: {
        expandTrigger: 'hover',
        label: 'cat_name',
        checkStrictly: true,
        value: 'cat_id'
      },
      //   切换按钮的属性类型
      activeName: 'many',
      //   添加用户数据双向绑定对象
      addForm: {},
      //   定义两个数组对象
      manyTableDate: [],
      onlyTabData: [],
      //   添加按钮弹出框
      addDialogVisible: false,
      //   编辑弹出框
      addEditDialogVisible: false,
      //   编辑数据双向绑定对象
      addEditForm: {},
      //   获取id
      editItemId: {},
      //   验证规则
      addFormRules: {
        attr_name: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          {
            min: 3,
            max: 15,
            message: '长度在 3 到 15 个字符',
            trigger: 'blur'
          }
        ],
        inputVisible: false,
        inputValue: ''
      }
    }
  },
  created () {
    this.getCateList()
  },
  methods: {
    async getCateList () {
      const { data: res } = await this.$http.get('categories')
      this.cateList = res.data
      console.log(res)
    },
    userCateChange () {
      // 如果数组长度不为3
      if (this.userCateKeys.length < 3) {
        this.userCateKeys = []
        this.manyTableDate = []
        this.onlyTabData = []
      }
      this.getPramsData()
    },
    // 声明函数为公共部分
    async getPramsData () {
      // 如果出现问题啊就返回
      if (this.cateId === undefined || this.cateId === null) return
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: { sel: this.activeName }
        }
      )
      res.data.forEach((item) => {
        //
        item.inputVisible = false
        item.inputValue = ''
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
      })
      if (this.activeName === 'many') {
        this.manyTableDate = res.data
      } else {
        this.onlyTabData = res.data
      }
      console.log(res)
    },
    // 切换按钮的事件
    handleClick () {
      this.getPramsData()
    },
    addAttr () {
      this.$refs.addFormRef.validate(async (isValue) => {
        if (!isValue) return
        // 调用计算事件 this.cateId
        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName
          }
        )
        if (res.meta.status !== 201) {
          this.$message.error(res.meta.msg)
        } else {
          this.$message({
            message: res.meta.msg,
            type: 'success'
          })
        }
        console.log(res)
        // 调用
        this.getPramsData()
        this.addDialogVisible = false
      })
    },
    // 编辑按钮弹出框
    async editAddList (itemId) {
      //   this.addEditForm = {}
      console.log(itemId)
      const { data: res } = await this.$http.get(
        `categories/${itemId.cat_id}/attributes/${itemId.attr_id}`)
      console.log(res)
      this.editItemId = res.data
      this.addEditForm = res.data
      this.addEditDialogVisible = true
    },
    // 编辑确定按钮
    async addEditAttr () {
      // console.log(this.editItemId.cat_id)
      // console.log(this.editItemId.attr_id)
      const { data: res } = await this.$http.put(
        `categories/${this.editItemId.cat_id}/attributes/${this.editItemId.attr_id}`,
        {
          attr_name: this.addEditForm.attr_name,
          attr_sel: this.activeName
        }
      )
      console.log(res)
      if (res.meta.status !== 200) {
        this.$message.error(res.meta.msg)
      } else {
        this.$message({
          message: '更新成功',
          type: 'success'
        })
      }
      this.getPramsData()
      this.addEditDialogVisible = false
    },
    // 删除按钮
    async editdelete (itemId) {
      console.log(itemId)
      const { data: res } = await this.$http.delete(
        `categories/${itemId.cat_id}/attributes/${itemId.attr_id}`
      )
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message({
          message: '删除失败',
          type: 'warning'
        })
      } else {
        this.$message({
          message: '删除成功',
          type: 'success'
        })
      }
      this.getPramsData()
    },
    showInput (row) {
      row.inputVisible = true
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    async handleInputConfirm (row) {
      row.inputVisible = false
      if (row.inputValue.trim().length !== 0) {
        row.attr_vals.push(row.inputValue)
        row.inputValue = ''
        await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
          attr_name: row.attr_id,
          attr_sel: this.activeName,
          attr_vals: row.attr_vals.join(' ')
        })
        this.getCateList()
      }
    },
    // 删除按钮
    async handleCloseCate (row, index) {
      row.attr_vals.splice(index, 1)
      await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`, {
        attr_name: row.attr_id,
        attr_sel: this.activeName,
        attr_vals: row.attr_vals.join(' ')
      })
    }
  },
  //   计算属性
  computed: {
    btnDisabled () {
      return this.userCateKeys.length !== 3
    },
    cateId () {
      return this.userCateKeys.length !== 3 ? null : this.userCateKeys[2]
    },
    titleText () {
      return this.activeName === 'only' ? '静态资源' : '动态参数'
    }
  }
}
</script>
<style lang="less" scoped>
.elrowCate {
  margin: 15px;
}
.el-tag + .el-tag {
    margin-left: 10px;
  }
  .button-new-tag {
    margin-left: 10px;
    height: 32px;
    line-height: 30px;
    padding-top: 0;
    padding-bottom: 0;
  }
  .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }
</style>
